package com.huawei.cloud.phone.management.common.utils;

import com.huawei.cloud.phone.management.common.exception.SystemInnerException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.UUID;

@Slf4j
public final class RandomStringUtils {
    private static final String ALL_CHAR = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    private static final int CHAR_NUMBER = ALL_CHAR.length();

    /**
     * 随机一个不含有横杠的32位长度的UUID
     *
     * @return UUID
     */
    public static String randomUuidNoHyphens() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    /**
     * 随机一个字符串
     *
     * @param strLength 字符串长度
     * @return 随机的字符串
     */
    public static String randomString(int strLength) {
        if (strLength < 0) {
            return StringUtils.EMPTY;
        }

        StringBuilder resultBuilder = new StringBuilder(strLength);
        SecureRandom random = new SecureRandom();
        for (int i = 0; i < strLength; i++) {
            resultBuilder.append(ALL_CHAR.charAt(random.nextInt(CHAR_NUMBER)));
        }
        return resultBuilder.toString();
    }

    /**
     * 随机一个128位长度的AES密钥
     *
     * @return 密钥
     */
    public static String randomAes128Key() {
        try {
            KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
            keyGenerator.init(128);
            SecretKey secretKey = keyGenerator.generateKey();
            return bytesToHex(secretKey.getEncoded());
        } catch (NoSuchAlgorithmException e) {
            log.error("gen aes key failed", e);
            throw new SystemInnerException();
        }
    }

    /**
     * 将数组转换成16进制的字符串
     *
     * @param bytes 字节数据
     * @return 字符串
     */
    public static String bytesToHex(byte[] bytes) {
        StringBuilder resultBuilder = new StringBuilder();
        for (byte b : bytes) {
            resultBuilder.append(String.format("%02X", b));
        }
        return resultBuilder.toString();
    }

}
